package com.dgut.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.admin.result.OrderExcelResult;
import com.dgut.admin.service.OrderService;
import com.dgut.common.entity.CollectionOrder;
import com.dgut.common.entity.OrderDetail;
import com.dgut.common.entity.UserInfo;
import com.dgut.common.enums.StatusEnum;
import com.dgut.common.mapper.CollectionOrderMapper;
import com.dgut.common.mapper.OrderDetailMapper;
import com.dgut.common.mapper.UserInfoMapper;
import com.dgut.common.param.OrderListParam;
import com.dgut.common.result.OrderDetailResult;
import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.PageVO;
import com.dgut.common.utils.ConvertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zyq
 * @Date 2022/4/10 11:42
 * @Description TODO
 * @Version 1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final CollectionOrderMapper orderMapper;
    private final OrderDetailMapper detailMapper;
    private final UserInfoMapper infoMapper;


    @Override
    public PageVO listOrder(OrderListParam param) {
        IPage<CollectionOrder> page = new Page<CollectionOrder>().setCurrent(param.getPageNum()).setSize(param.getPageSize());
        IPage<CollectionOrder> orderIPage = orderMapper.selectPage(page, getWrapper(param));
        return PageVO.convert(orderIPage);
    }

    @Override
    public OrderDetailResult detail(String id) {
        CollectionOrder collectionOrder = orderMapper.selectById(id);
        if (collectionOrder == null) {
            throw new ApiException("订单信息不存在");
        }
        UserInfo eInfo = infoMapper.selectByUserId(collectionOrder.getEmployerId(), StatusEnum.SUCCESS_AUDIT.getState());
        UserInfo cInfo = infoMapper.selectByUserId(collectionOrder.getCollectorId(), StatusEnum.SUCCESS_AUDIT.getState());

        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", id);
        List<OrderDetail> orderDetails = detailMapper.selectList(wrapper);

        return OrderDetailResult.builder()
                .order(collectionOrder)
                .employer(eInfo)
                .collector(cInfo)
                .details(orderDetails)
                .build();
    }

    @Override
    public List<OrderExcelResult> excelData(OrderListParam param) {
        return orderMapper.selectList(getWrapper(param)).stream()
                .map(e -> OrderExcelResult.builder()
                .id(e.getId())
                .employerName(e.getEmployerName())
                .collectorName(e.getCollectorName())
                .amount(ConvertUtil.fenToYuan(e.getAmount()))
                .totalWeight(ConvertUtil.gToKg(e.getTotalWeight()))
                .state(ConvertUtil.getState(e.getState()))
                .address(e.getAddress())
                .remark(e.getRemark())
                .createTime(e.getCreateTime())
                .finishTime(e.getFinishTime())
                .subscriptionTime(e.getSubscriptionTime())
                .build()).collect(Collectors.toList());
    }


    /**
     * 根据订单筛选条件生成Wrapper
     * @param param 筛选参数
     * @return QueryWrapper
     */
    private QueryWrapper<CollectionOrder> getWrapper(OrderListParam param) {
        QueryWrapper<CollectionOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (param.getBeginTime() != null && param.getEndTime() != null) {
            wrapper.between("create_time", param.getBeginTime(), param.getEndTime());
        }

        if (param.getState() != null && !Integer.valueOf(-1).equals(param.getState())) {
            wrapper.eq("state", param.getState());
        }

        if (param.getName() != null && !"".equals(param.getName())) {
            wrapper.likeLeft("employer_name", param.getName()).or().likeLeft("collector_name", param.getName());
        }
        return wrapper;
    }
}
